package com.cxs.xiaomi.web.filter;

import com.cxs.xiaomi.domain.User;
import com.cxs.xiaomi.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

/*
 * @Author:cxs
 * @Date:2021/9/14  15:55
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * 七天免登录过滤器
 * */
@WebFilter(filterName = "AutoLoginFilter", urlPatterns = {"/","/login.jsp"})
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("loginCookie")) {
                    // 说明cookie没有失效，免登录
                    String value = cookie.getValue();
                    String decode = URLDecoder.decode(value, "utf-8");
                    String preStr = decode.split(":")[0];
                    if (preStr != null && preStr.length() > 0) {
                        String userId = preStr.substring(preStr.lastIndexOf("_") + 1);
                        if (userId != null && userId.length() > 0) {
                            User user = new UserServiceImpl().findById(userId);
                            HttpSession session = request.getSession();
                            session.setAttribute("user", user);
                            response.sendRedirect(request.getContextPath() + "/index.jsp");
                            return;
                        }
                    }else{
                        // 清除cookie
                        Cookie loginCookie = new Cookie("loginCookie", null);
                        loginCookie.setPath(request.getContextPath());
                        loginCookie.setMaxAge(0);
                        response.addCookie(loginCookie);
                        response.sendRedirect(request.getContextPath() + "/login.jsp");
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }
}
